package com.siecomzg.transport.handler;

import android.os.Bundle;

import com.siecomzg.constconfig.ConstDefine;
import com.siecomzg.proto.Message;
import com.siecomzg.transport.CallbackMap;
import com.siecomzg.transport.CommonClient;
import com.siecomzg.transport.DeviceCallback;
import com.siecomzg.transport.SiecomDevice;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

/**
 * Created on 2017/1/16.
 */

public abstract class CommonHandler implements ServiceHandler {

    private static CallbackMap callbackMap = CallbackMap.getInstance();


    public void sendMessage(Message.siecomproto msg,String msgStr, DeviceCallback callback, boolean isOnMain) {

        int requestCmd = msg.getCmd();
        String msgid = msg.getMsgid();

        if (requestCmd == ConstDefine.UPDATE_FW_REQUEST){
            try {
                JSONObject jb = new JSONObject(msg.getRequest());
                int num = jb.getInt("num");
                int total = jb.getInt("total");
                if (num == 1 || num == total)
                    callbackMap.addCallbackTask(msg, callback, msg.getTimeout(), isOnMain);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }else
            callbackMap.addCallbackTask(msg, callback, msg.getTimeout(), isOnMain);

        if (msg.getModule() != ConstDefine.UPDATE_MODULE){
            SiecomDevice.deliverResult(callback, SiecomDevice.Result.START, new Bundle(), isOnMain);
        }
        try {
            SiecomDevice.sendToRemote(msg,msgStr);
        } catch (IOException e) {
            e.printStackTrace();
            Bundle bundle = new Bundle();
            bundle.putString("message", e.getMessage());
            bundle.putInt("code", e.hashCode());
            SiecomDevice.deliverResult(callback, SiecomDevice.Result.ERROR, bundle, isOnMain);

        }


    }


    @Override
    public abstract void onReceive(CommonClient server, Message.siecomproto msg);


}
